package web.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Iterator;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;

import play.libs.Json;
public class ResultCode {

	public static final String SUCCESS = "success";
	public static final String FAIL = "fail";
	public static final String ERROR = "error";

	public static enum ajaxResult {
		SUCCESS,// 
		ERROR,//
		;
		private List<String> errrorMessage;
		private Map<String, String> ajaxData;
        
		public void setErrorMessage(List<String >errorMessage){
			this.errrorMessage=errorMessage;
		}
		public void setAjaxData(Map<String,String>data){
			this.ajaxData=data;
		}
		public ObjectNode toJson(){
			//ObjectNode result = Json.newObject();
			JsonFactory factory = new JsonFactory();
			ObjectMapper om = new ObjectMapper(factory);
			factory.setCodec(om);
			ObjectNode result = om.createObjectNode();
			result.put("ajaxResult", this.name().toLowerCase());
			if(null!=errrorMessage&&this.errrorMessage.size()>0){
				ArrayNode errors = om.createArrayNode();
				for(String errorItem:errrorMessage){
					errors.add(errorItem);
				}
				//errorsNode.put(fieldName, v)
				result.put("ajaxErrors", errors);
				
			}
			if(null!=ajaxData&&this.ajaxData.size()>0){
				ObjectNode item = Json.newObject();
				Set<Entry<String,String>> set=this.ajaxData.entrySet();
				Iterator<Entry<String,String>> it = set.iterator();
				while(it.hasNext()){
					Entry<String,String> entry=it.next();
					item.put(entry.getKey(), entry.getValue());
				}
				result.put("ajaxData", item);
			}
			return result;
		}
		public String toString(){
			String result="{\"ajaxResult\":\""+this.name().toLowerCase()+"\"";
			if(null!=errrorMessage&&this.errrorMessage.size()>0){
				result+=",\"ajaxErrors\":[";
				for(String errorItem:errrorMessage){
					result+="{\""+errorItem+"\"},";
				}
				result=result.substring(0, result.length()-1);
				result+="]";
			}
			if(null!=this.ajaxData&&this.ajaxData.size()>0){
				result+=",\"ajaxData\":[";
				Set<Entry<String,String>> set=this.ajaxData.entrySet();
				Iterator<Entry<String,String>> it = set.iterator();
				while(it.hasNext()){
				  Entry<String,String> entry=it.next();
				  result+="{\""+entry.getKey()+"\":\""+entry.getValue()+"\"},"; 	
				}
				result=result.substring(0, result.length()-1);
				result+="]";
			}
			result+="}";
			return result;
		}
		
	}
}
